<template>
  <div class="wrapper">
    <!-- 顶部 -->
    <header class="topbar">
      <h1 class="title">创建店铺</h1>
      <div class="actions">
        <el-button @click="goBack">返回</el-button>
        <el-button type="primary" :loading="submitting" @click="submitForm">提交</el-button>
      </div>
    </header>

    <div class="container">
      <el-form ref="formRef" :model="business" :rules="rules" label-width="120px" label-position="left">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12">
            <el-form-item label="店铺名称" prop="businessName">
              <el-input v-model="business.businessName" placeholder="请输入店铺名称" clearable />
            </el-form-item>

            <el-form-item label="店铺图片">
              <el-input v-model="business.businessImg" placeholder="请输入图片URL或选择文件" clearable />
              <div class="img-tools">
                <input ref="fileInput" type="file" accept="image/*" @change="onPickImage" />
                <small class="hint">选择图片仅做本地Base64预览；若后端有上传接口再对接。</small>
              </div>
              <div v-if="business.businessImg" class="img-preview">
                <img :src="business.businessImg" alt="预览" />
              </div>
            </el-form-item>

            <el-form-item label="店铺地址" prop="businessAddress">
              <el-input v-model="business.businessAddress" placeholder="请输入店铺地址" clearable />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12">
            <el-form-item label="起送价" prop="startPrice">
              <el-input-number v-model="business.startPrice" :min="0" :precision="2" :step="1" />
            </el-form-item>

            <el-form-item label="配送价" prop="deliveryPrice">
              <el-input-number v-model="business.deliveryPrice" :min="0" :precision="2" :step="1" />
            </el-form-item>

            <el-form-item label="店铺描述">
              <el-input type="textarea" :rows="4" v-model="business.businessExplain" placeholder="请输入店铺描述"
                maxlength="200" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'

export default {
  name: 'BusinessCreate',

  data() {
    return {
      token: '',
      user: null,
      submitting: false,
      business: {
        businessName: '',
        businessImg: '',
        businessAddress: '',
        startPrice: 0,
        deliveryPrice: 0,
        businessExplain: '',
        status: 'PENDING',   // 如果后端没有这个字段，不会报错，但可去掉
        isOpen: false        // 同上
      },
      user: {}
    }
  },
  created() {
    this.token = localStorage.getItem('token')
    this.$axios.get(`/user`, {
      headers: {
        'Authorization': `Bearer ${this.token}`
      }
    }).then(response => {
      this.user = response.data.data;
    }).catch(error => {
      console.error(error);
    });
  },
  methods: {
    goBack() {
      this.$router.push({ path: '/mine' });
    },

    onPickImage(e) {
      const file = e.target.files && e.target.files[0]
      if (!file) return
      const reader = new FileReader()
      reader.onload = () => { this.business.businessImg = reader.result }
      reader.readAsDataURL(file)
    },

    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return
        this.saveBusiness()
      })
    },

    // 提交：明确走 businesses（与你的后端匹配）
    saveBusiness() {
      if (this.submitting) return
      this.submitting = true

      this.$axios.post('businesses', {
        "businessOwner": {
          "id": this.user.id
        },
        "businessName": this.business.businessName,
        "businessAddress": this.business.businessAddress,
        "businessExplain": this.business.businessExplain,
        "businessImg": this.business.businessImg,
        "orderTypeId": this.business.orderTypeId,
        "startPrice": this.business.startPrice,
        "deliveryPrice": this.business.deliveryPrice,
        "remarks": this.business.remarks
      }, {
        headers: { Authorization: `Bearer ${this.token}`, 'Content-Type': 'application/json' }
      })
        .then(res => {
          const data = res?.data
          const created = data?.data || null
          const ok = created || data?.code === 0 || data?.success === true
          if (!ok) throw new Error(data?.msg || data?.message || '创建失败')
          ElMessage.success('创建成功')
          this.goBack()
        })
        .catch(err => {
          const s = err?.response?.status
          const msg = s === 401 ? '未登录或 Token 失效'
            : s === 403 ? '无权限'
              : err?.response?.data?.message || err?.message || '创建失败'
          ElMessage.error(msg)
        })
        .finally(() => { this.submitting = false })
    }
  }
}
</script>

<style scoped>
/* 主题色（#0099FF） */
.wrapper {
  --primary: #0099ff;
  --bg: #f6f8fb;
}

.wrapper {
  min-height: 100vh;
  background: var(--bg);
}

/* 顶部栏 */
.topbar {
  position: sticky;
  top: 0;
  z-index: 10;
  height: 56px;
  padding: 0 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: var(--primary);
  color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, .06);
}

.title {
  font-size: 18px;
  font-weight: 600;
}

.actions :deep(.el-button + .el-button) {
  margin-left: 8px;
}

/* 内容容器：为底部 Footer 预留空间（你的 Footer ≈14vw） */
.container {
  max-width: 960px;
  margin: 0 auto;
  padding: 16px;
  padding-bottom: calc(14vw + 16px);
}

/* 图片工具与预览 */
.img-tools {
  margin-top: 8px;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.img-tools input[type="file"] {
  max-width: 260px;
}

.hint {
  color: #8b98a5;
  font-size: 12px;
}

.img-preview {
  margin-top: 10px;
}

.img-preview img {
  max-width: 320px;
  max-height: 180px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, .06);
}
</style>
